package com.wn55.hrms.util;

import com.wn55.hrms.service.vo.JwtInfo;
import io.jsonwebtoken.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

public class JwtUtil {
    private static final Properties properties = new Properties();
    private static JwtUtil jwtUtil = null;

    private JwtUtil(){}


    public static JwtUtil getInstance(){
        if (jwtUtil == null){
            synchronized (JwtUtil.class){
              if (jwtUtil == null){

                    jwtUtil = new JwtUtil();
              }
            }
        }
        return jwtUtil ;
    }

    //加载jwt.properties配置文件
    static {
        InputStream in = JwtUtil.class.getClassLoader().getResourceAsStream("jwt.properties");
        //把jwt中的配置信息 解析加载到 properties集合中
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成Token
     * @param jwtInfo  token中的自定义信息
     * @return 1
     */
    public String createToken(JwtInfo jwtInfo){
        try {
            //构建出一个Jwt的构建者对象
            JwtBuilder jwtBuilder = Jwts.builder();
            //设置头信息
            jwtBuilder.setHeaderParam("alg",properties.getProperty("alg"));
            jwtBuilder.setHeaderParam("typ",properties.getProperty("typ"));

            //设置载荷信息
            jwtBuilder.setIssuer(properties.getProperty("issuer"));
            jwtBuilder.setSubject(properties.getProperty("suject"));
            //设置过期时间  30分钟
            jwtBuilder.setExpiration(new Date(System.currentTimeMillis()+Long.parseLong(properties.getProperty("expiration"))));

            //设置自定义信息
            jwtBuilder.claim(properties.getProperty("userName"),jwtInfo.getUserName());
            //不建议设置密码

            //设置 签证信息
            final String SECRET = properties.getProperty("secret");

            //做签证
            jwtBuilder.signWith(SignatureAlgorithm.HS256,SECRET);
            return jwtBuilder.compact();


        }catch (RuntimeException e){
            e.printStackTrace();
            throw new RuntimeException("JWT的token生成失败",e);
        }
    }

    /**
     * 解析JWT的token
     * @param token 1
     * @return 1
     */
    public Claims parseToken(String token){
        try {
            JwtParser jwtParser = Jwts.parser();
            Jws<Claims> claimsJws = jwtParser.setSigningKey(properties.getProperty("secret")).parseClaimsJws(token);
            return claimsJws.getBody();


        }catch (ExpiredJwtException e){
            e.printStackTrace();
            throw  new ExpiredJwtException(null,null,"token已经过期！",e);
        }catch (SignatureException e1){
            e1.printStackTrace();
            throw new SignatureException("密钥不正确！",e1);
        }catch (RuntimeException e2){
            e2.printStackTrace();
            throw new RuntimeException("解析token出错！",e2);
        }
    }

}
